﻿using SmartHotel.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartHotel.DAL
{
    public class ProductDAL
    {
        public ProductDAL(HotelContext hotelContext)
        {
            HotelContext = hotelContext;
        }

        public HotelContext HotelContext { get; }

        /// <summary>
        /// 添加商品的数据访问层方法  
        /// </summary>
        /// <param name="product">商品对象</param>
        /// <returns></returns>
        public int AddProduct(Product product)
        {
            product.CreateTime = DateTime.Now;

            var 雪花id = Yitter.IdGenerator.YitIdHelper.NextId();
            product.Code = 雪花id.ToString();


            HotelContext.Products.Add(product);
            return HotelContext.SaveChanges();
        }
        /// <summary>
        /// 根据id查找商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Product GetProductById(int id)
        {

            return HotelContext.Products.Where(x => x.Id == id).FirstOrDefault();
        }

        public int UpdateProduct(Product product)
        {
            var product1 = GetProductById(product.Id);  //根据id找到要更新的商品
            if (product1 != null)
            {
                product1.Name = product.Name;
                product1.Description = product.Description;
                product1.Price = product.Price;
                product1.Stock = product.Stock;
                product1.Status = product.Status;
                product1.UpdateTime = DateTime.Now;
                product1.ImgUrl = product.ImgUrl;
            }
            return HotelContext.SaveChanges();
        }
        /// <summary>
        /// 物理删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteProduct(int id)
        {
            var product1 = GetProductById(id);  //根据id找到要删除的商品
            if (product1 != null)
            {
                HotelContext.Products.Remove(product1);
            }
            return HotelContext.SaveChanges();
        }
        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int LogicDelte(int id)
        {
            var product1 = GetProductById(id);  //根据id找到要逻辑删除的商品

            if (product1 != null)
            {
                product1.IsDeleted = true;
            }
            return HotelContext.SaveChanges();
        }

        public List<Product> GetProductPages(int index, int size, out int count, string? Name, DateTime? beginTime, DateTime? endTime)
        {
            var products = HotelContext.Products.AsQueryable();// select * from products;
            products = products.Where(x => x.IsDeleted == false); //逻辑删除:过滤掉isdeleted=true  //重点

            if (!string.IsNullOrEmpty(Name))
            { //如果前端传过来一个Name,这个Name不为空
                products = products.Where(p => p.Name.Contains(Name));//模糊查询  select * from products where name like'%@name%';
            }
            if (beginTime != null)
            {
                products = products.Where(x => x.CreateTime >= beginTime); //按照时间范围查询
            }
            if (endTime != null)
            {
                products = products.Where(x => x.CreateTime <= endTime); //按照时间范围查询
            }

            count = products.Count();

            return products
                    .OrderByDescending(x => x.Id)//orderby 12345  orderbydesc  654321
                    .Skip((index - 1) * size)
                    .Take(size)//取
                    .ToList();
        }

        /// <summary>
        /// 考前突击 分页方法
        /// </summary>
        /// <param name="index">当前页</param>
        /// <param name="size">每页行数</param>
        /// <param name="count">总条数</param>
        /// <param name="productName">查询条件</param>
        /// <returns></returns>
        public List<Product> GetProductFenYe(int index, int size, out int count, string? productName)
        {

            var products = HotelContext.Products.AsQueryable();

            if (!string.IsNullOrEmpty(productName))
            {
                products = products.Where(x => x.Name.Contains(productName));
            }

            count = products.Count(); //总条数

            return products
                .OrderByDescending(x => x.NeedJifen)
                .OrderByDescending(x => x.Id)
                .Skip((index - 1) * size)
                .Take(size)
                .ToList();
        }

        /// <summary>
        /// username 兑换 productid 对应的商品
        /// </summary>
        /// <param name="userName">userName</param>
        /// <param name="productId">商品id</param>
        /// <returns></returns>
        public int DuiHuan(string userName, int productId)
        {

            int result = -7;//返回结果

            using (var trans = HotelContext.Database.BeginTransaction())
            {

                try
                {
                    var product = HotelContext.Products.Where(x => x.Id == productId).FirstOrDefault(); //找到要兑换的商品
                 
                    if (product == null)
                    {
                        result = -1;//商品不存在
                        throw new Exception("兑换过程中出现异常");
                    }
                    else
                    {

                        if (product.Status == 0)
                        {
                            result = -2;//商品下架
                            throw new Exception("兑换过程中出现异常");
                        }
                        else
                        {

                            if (product.Stock < 1)
                            {
                                result = -3;//商品库存不足
                                throw new Exception("兑换过程中出现异常");
                            }
                        }


                        var  user = HotelContext.Members.Where(x => x.Name == userName).FirstOrDefault();
                        if (user == null)
                        {
                            result = -4;//登录用户不存在
                            throw new Exception("兑换过程中出现异常");
                        }
                        else if (user.JifenVal < product.NeedJifen)
                        {
                            result = -5; //用户积分不足
                            throw new Exception("兑换过程中出现异常");
                        }
                        else
                        {//所有校验都通过

                            product.Stock = product.Stock - 1;//库存扣除1

                            user.JifenVal = user.JifenVal - product.NeedJifen;

                            JiFen jifen = new JiFen();
                            jifen.Time = DateTime.Now;
                            jifen.UserId = user.Id;
                            jifen.JiFenCount = -product.NeedJifen;
                            jifen.Reason = "用户:" + user.Name + "兑换了" + product.Name + ",使用积分数量:" + product.NeedJifen;

                            HotelContext.JiFens.Add(jifen);

                           
                        }
                    }

                     
                      
                     


                    HotelContext.SaveChanges();// begin transcation .... end 

                    trans.Commit();
                    result = 1;//最终成功!!!!!!!!!!!!!!!!!!1
                }
                catch (Exception)
                {
                    //result = -6;//保存异常
                    trans.Rollback();

                }

            }
            return result;
        }
    }
}
